`
https://leetcode.cn/problems/maximum-coins-from-k-consecutive-bags/
`

/**
 * @param {number[][]} coins
 * @param {number} k
 * @return {number}
 */
var maximumCoins = function (coins, k) {
  // 在 2271 题的基础上，额外跑一遍和左端点对齐的滑动窗口即可
  // 把 coins 反转，每个区间 [l, r] 改为 [−r, −l]，就可以直接复用代码
  coins.sort((a, b) => a[0] - b[0])
  const res = maximumWhiteTiles(coins, k)

  coins.reverse()
  for (const coin of coins) {
    [coin[0], coin[1]] = [-coin[1], -coin[0]]
  }
  return Math.max(res, maximumWhiteTiles(coins, k))
};

// https://leetcode.cn/problems/maximum-white-tiles-covered-by-a-carpet/
// 改了加权
var maximumWhiteTiles = function (tiles, carpetLen) {
  const n = tiles.length
  tiles.sort((a, b) => a[0] - b[0])
  let res = 0
  let cover = 0
  let left = 0, right = 0
  while (right < n) {
    const [tl, tr, tw] = tiles[right++]
    // 加权
    cover += (tr - tl + 1) * tw
    const carpetLeft = tr - carpetLen + 1
    while (tiles[left][1] < carpetLeft) {
      // 加权
      cover -= (tiles[left][1] - tiles[left][0] + 1) * tiles[left][2]
      left++
    }
    // 加权
    const uncover = Math.max((carpetLeft - tiles[left][0]) * tiles[left][2], 0)
    res = Math.max(res, cover - uncover)
  }
  return res
};